/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.smart.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.concurrent.Callable;

/**
 * 分片上传任务
 * @author zhanghong
 * @version UploadPartTask.java, v 0.1 2023/8/8 18:26 下午 UploadPartTask Exp $$
 */
@Slf4j
public class UploadPartTask implements Callable<PartETag> {

    private MultipartFile multipartFile;
    private String uploadId;
    private int partNumber;
    private long startPos;
    private long endPos;
    private OSS ossClient;
    private String buckName;

    public UploadPartTask(String buckName, MultipartFile multipartFile, String uploadId, int partNumber,
                          long startPos, long endPos, OSS ossClient) {
        this.buckName = buckName;
        this.multipartFile = multipartFile;
        this.uploadId = uploadId;
        this.partNumber = partNumber;
        this.startPos = startPos;
        this.endPos = endPos;
        this.ossClient = ossClient;
    }

    @Override
    public PartETag call() throws Exception {
        InputStream inputStream = null;
        try {
            log.info("uploadMultipartFile... 分片数：{}", partNumber);
            ByteArrayResource resource = new ByteArrayResource(StreamUtils.copyToByteArray(multipartFile.getInputStream())) {
                @Override
                public String getFilename() {
                    return multipartFile.getOriginalFilename();
                }
            };
            inputStream = resource.getInputStream();
            inputStream.skip(startPos);
            UploadPartRequest uploadRequest = new UploadPartRequest();
            uploadRequest.setBucketName(buckName);
            uploadRequest.setKey(uploadId);
            uploadRequest.setUploadId(uploadId);
            uploadRequest.setPartNumber(partNumber);
            uploadRequest.setPartSize(endPos - startPos);
            uploadRequest.setInputStream(inputStream);
            UploadPartResult uploadResult = ossClient.uploadPart(uploadRequest);
            return uploadResult.getPartETag();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return null;
    }
}
